$(function (){
    //获得地址栏中的id
    var goodData = {};
    let queryString = location.search;  //?pid=14
    let id = queryString.split("=")[1];
    fetch(`load.product?id=${id}`).then(response=>response.json()).then(data=>{
        console.log(data.data);
        document.title = `${data.data.goodsItem.title}`;
        // console.log(typeof data.data);
        goodData=data.data;

        let bigimgIndex = 0;

        //路径导航的数据渲染
        navPathDataBind();
        function navPathDataBind() {
            let navPath = document.querySelector('#content .contentMain #navPath');
            let path = goodData.path;
            console.log("path:"+path);
            if(path.length>0){
                let pathHeader = document.createElement('p');
                pathHeader.innerHTML=`您当前的位置 :&nbsp&nbsp&nbsp<a href="index.html">首页</a><i>/</i>`
                navPath.appendChild(pathHeader);
            }
            //3.遍历数据
            for (let i = 0; i < path.length; i++) {
                if (i == path.length - 1) {
                    let aNode = document.createElement("a");
                    aNode.innerText = path[i].title;
                    navPath.appendChild(aNode);
                } else {
                    let aNode = document.createElement("a");
                    aNode.href = path[i].url;
                    aNode.innerText = path[i].title;
                    let iNode = document.createElement('i');
                    iNode.innerText = '/';
                    navPath.appendChild(aNode);
                    navPath.appendChild(iNode);
                }
            }
        }

        //放大镜的移入、移出效果
        bigClassBind();
        function bigClassBind() {
            let smallPic = document.querySelector('#content .contentMain #center #left #leftTop #smallPic');
            let leftTop = document.querySelector('#content .contentMain #center #left #leftTop');
            let imagessrc = goodData.imagessrc;

            smallPic.onmouseenter = function () {
                let maskDiv = document.createElement('div');
                maskDiv.className = "mask";
                let BigPic = document.createElement('div');
                BigPic.id = "bigPic";
                let BigImg = document.createElement('img');
                BigImg.src = imagessrc[bigimgIndex].b;
                BigPic.appendChild(BigImg);
                smallPic.appendChild(maskDiv);
                leftTop.appendChild(BigPic);
                smallPic.onmousemove = function (event) {
                    let left = event.clientX - smallPic.getBoundingClientRect().left - maskDiv.offsetWidth / 2;
                    let top = event.clientY - smallPic.getBoundingClientRect().top - maskDiv.offsetHeight / 2;
                    if (left < 0) {
                        left = 0;
                    } else if (left > smallPic.clientWidth - maskDiv.offsetWidth) {
                        left = smallPic.clientWidth - maskDiv.offsetWidth;
                    }
                    if (top < 0) {
                        top = 0;
                    } else if (top > smallPic.clientHeight - maskDiv.offsetHeight) {
                        top = smallPic.clientHeight - maskDiv.offsetHeight;
                    }
                    maskDiv.style.left = left + "px";
                    maskDiv.style.top = top + "px";
                    let scale = (smallPic.clientWidth - maskDiv.offsetWidth) / (BigImg.offsetWidth - BigPic.clientWidth)
                    BigImg.style.left = -left / scale + 'px';
                    BigImg.style.top = -top / scale + 'px';
                }
                smallPic.onmouseleave = function () {
                    smallPic.removeChild(maskDiv);
                    leftTop.removeChild(BigPic);
                }
            }
        }

        //动态渲染放大镜缩略图的数据
        thumbnailData();
        function thumbnailData() {
            let ul = document.querySelector('#content .contentMain #center #left #leftBottom #piclist ul');
            let imagessrc = goodData.imagessrc;
            for (let i = 0; i < imagessrc.length; i++) {
                let newLi = document.createElement('li');
                let newImg = document.createElement('img');
                newImg.src = imagessrc[i].s;
                newLi.appendChild(newImg);
                ul.appendChild(newLi);
            }
        }

        //点击缩略图的效果
        thumbnailClick();
        function thumbnailClick() {
            let liNodes = document.querySelectorAll('#content .contentMain #center #left #leftBottom #piclist ul li');
            let smallPic_img = document.querySelector('#content .contentMain #center #left #leftTop #smallPic img');
            let imagessrc = goodData.imagessrc;
            smallPic_img.src = imagessrc[0].s;
            for (let i = 0; i < liNodes.length; i++) {
                liNodes[i].index = i;
                liNodes[i].onclick = function () {
                    let idx = this.index;
                    bigimgIndex = idx;
                    smallPic_img.src = imagessrc[idx].s;
                }
            }
        }

        //商品详情数据的动态渲染
        rightTopData();
        function rightTopData() {
            let rightTop = document.querySelector('#content .contentMain #center #right .rightTop');
            let goodsItem = goodData.goodsItem;
            function getstartdate(day) {
                var curr_time = new Date();
                var week_time = new Date(curr_time.getTime() - 1000 * 60 * 60 * 24 * day);
                return week_time;
            }
            let s = `<h3>${goodsItem.title}</h3>
            <div class="priceWrap">
                <div class="priceTop">
                    <span>价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格</span>
                    <div class="price">
                        <span>￥</span>
                        <p>${goodsItem.price}</p>
                        <a herf="#">降价通知</a>
                    </div>
                    <p>
                        <span>累计评价</span>
                        <span>${goodsItem.evaluateNum}</span>
                    </p>
                </div>
                <div class="priceBottom">
                    <span>促&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销</span>
                    <p>
                        <span>${goodsItem.promoteSales.type}</span>
                        <span>${goodsItem.promoteSales.content}</span>
                    </p>
                </div>
            </div>
            <div class="support">
                <span>支&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;持</span>
                <p>${goodsItem.support}</p>
            </div>
            <div class="address">
                <span>所&nbsp;在&nbsp;地</span>
                <p>${goodsItem.address}</p>
                <p>由官方旗舰店发货, 并提供售后服务. 现在至明日16:00前完成下单，预计${getstartdate(-1).getMonth()+1}月${getstartdate(-1).getDate()}日20:00前发货，${getstartdate(-4).getMonth()+1}月${getstartdate(-4).getDate()}日24:00前送达</p>
            </div>`;
            rightTop.innerHTML = s;
        }

        //商品参数数据的动态渲染
        rightBottomData();
        function rightBottomData() {
            let chooseWrap = document.querySelector('#content .contentMain #center #right .rightBottom .chooseWrap');
            let crumbData = goodData.goodsItem.crumbData;
            for (let i = 0; i < crumbData.length; i++) {
                let dlNode = document.createElement('dl');
                let dtNode = document.createElement('dt');
                dtNode.innerText = crumbData[i].title;
                dlNode.appendChild(dtNode);
                for (let j = 0; j < crumbData[i].data.length; j++) {
                    let ddNode = document.createElement('dd');
                    ddNode.innerText = crumbData[i].data[j].type;
                    ddNode.setAttribute('price', crumbData[i].data[j].changePrice);
                    dlNode.appendChild(ddNode);
                }
                chooseWrap.appendChild(dlNode);
            }
        }

        //点击商品参数之后的颜色排他效果
        clickddBind();
        function clickddBind() {
            let dlNodes = document.querySelectorAll('#content .contentMain #center #right .rightBottom .chooseWrap dl');
            let arr = new Array(dlNodes.length);
            let choose = document.querySelector('#content .contentMain #center #right .rightBottom .choose');
            arr.fill(0);
            for (let i = 0; i < dlNodes.length; i++) {
                (function (i) {
                    let ddNodes = dlNodes[i].querySelectorAll('dd');
                    for (let j = 0; j < ddNodes.length; j++) {
                        ddNodes[j].onclick = function () {
                            // console.log(i);
                            //  console.log(ddNodes[i]);
                            // console.log(this);
                            //清空choose元素
                            choose.innerHTML = "";
                            for (let k = 0; k < ddNodes.length; k++) {
                                ddNodes[k].style.color = "#666";
                                ddNodes[k].className = "";
                            }
                            this.style.color = "#f10180";
                            this.className = "selected";
                            arr[i] = this;
                            changePriceBind(arr);
                            arr.forEach(function (value, index) {
                                if (value) {
                                    let markDiv = document.createElement('div');
                                    markDiv.className = 'mark';
                                    markDiv.innerText = value.innerText;
                                    let aNode = document.createElement('a');
                                    aNode.innerText = 'X';
                                    aNode.setAttribute('index', index);
                                    markDiv.appendChild(aNode);
                                    choose.appendChild(markDiv);
                                }
                            })
                            let aNodes = document.querySelectorAll('#content .contentMain #center #right .rightBottom .choose .mark a');
                            for (let n = 0; n < aNodes.length; n++) {
                                aNodes[n].onclick = function () {
                                    let idx1 = this.getAttribute('index');
                                    arr[idx1] = 0;
                                    let ddlist = dlNodes[idx1].querySelectorAll('dd');
                                    for (let m = 0; m < ddlist.length; m++) {
                                        ddlist[m].style.color = "#666";
                                        ddlist[m].className = "";
                                    }
                                    ddlist[0].style.color = '#f10180';
                                    ddlist[0].className = "selected";
                                    choose.removeChild(this.parentNode);
                                    changePriceBind(arr);
                                }
                            }
                        }
                        ddNodes[0].className="selected";
                    }
                })(i)
            }

            //监视商品数量input
            //增加减少数量改变价格
            //首先保障点击有效
            let countInput = document.querySelector("#content .contentMain #center #right .rightBottom .addCart .count input");
            $("#content .contentMain #center #right .rightBottom .addCart .count button").eq(0).on("click",function
                (){
                let count =Number($("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value")) + 1;
                $("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value",`${count}`);
                $("#content .contentMain #center #right .rightBottom .addCart .count button").eq(1).prop("disabled","");
                changePriceBind(arr)
            })
            $("#content .contentMain #center #right .rightBottom .addCart .count button").eq(1).on("click",function
                (){
                if(Number($("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value"))<=1){
                    $("#content .contentMain #center #right .rightBottom .addCart .count button").eq(1).prop("disabled","true")
                }else{
                    let count =Number($("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value")) - 1;
                    $("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value",`${count}`);
                    changePriceBind(arr)
                }
            })
            //失去焦点
            countInput.addEventListener("blur",()=>{
                changePriceBind(arr)
            })
            //按下回车
            countInput.addEventListener("keydown",()=>{
                changePriceBind(arr)
            })
        }

        //价格变动的函数
        function changePriceBind(arr) {
            let oldPrice = document.querySelector('#content .contentMain #center #right .rightTop .priceWrap .priceTop .price p');
            //取出默认的价格
            let price = goodData.goodsItem.price;
            for (let i = 0; i < arr.length; i++) {
                if (arr[i]) {
                    let changeprice = Number(arr[i].getAttribute('price'));
                    price += changeprice;
                }
            }
            oldPrice.innerText = price * Number($("#content .contentMain #center #right .rightBottom .addCart .count input").prop("value"));
        }



        // 商品详细开始

        //尺寸隐藏开始
        sizeHidden();
        function sizeHidden(){
            $("#size-help-up").on("click",()=>{
                $(".size-table-wrap").css({
                    "height":"181px"
                })
                $("#size-help-up").css("display","none");
                $("#size-help-more").css("display","block");
            })
            $("#size-help-more").on("click",()=>{
                $(".size-table-wrap").css({
                    "height":"469px"
                })
                $("#size-help-more").css("display","none");
                $("#size-help-up").css("display","block");
            })
        }
        //尺寸隐藏结束

        //商品隐藏开始
        goodsHidden();
        function goodsHidden(){
            $("#goods-details-up").on("click",()=>{
                $(".goods-details-content").css({
                    "height":"161px"
                })
                $("#goods-details-up").css("display","none");
                $("#goods-details-more").css("display","block");
            })
            $("#goods-details-more").on("click",()=>{
                let height = $(".goods-details-content tr").length*40+1;
                $(".goods-details-content").css({
                    "height":`${height}`
                })
                $("#goods-details-more").css("display","none");
                $("#goods-details-up").css("display","block");
            })
        }
        //商品隐藏结束
        // 商品详细结束

        //商品数据渲染
        //参数渲染
        goodsDetails();
        function goodsDetails(){
            let tr = '';
            for(let i=0;i<goodData.goodsDetails.length;i+=2){
                if(goodData.goodsDetails[i]&&goodData.goodsDetails[i+1]){
                    tr += `<tr>
            <th class="goods-details-content-tit">${goodData.goodsDetails[i].title}：</th>
            <td>${goodData.goodsDetails[i].data}</td>
            <th class="goods-details-content-tit">${goodData.goodsDetails[i+1].title}：</th>
            <td>${goodData.goodsDetails[i+1].data}</td>
            </tr>`;
                }else{
                    tr +=`<tr>
                <th class="goods-details-content-tit">${goodData.goodsDetails[i].title}：</th>
                <td>${goodData.goodsDetails[i].data}</td>
                <th class="goods-details-content-tit"></th>
                <td></td>
                </tr>`
                }
            }
            let goodsDetailsContent = document.querySelector(".goods-details-content tbody");
            goodsDetailsContent.innerHTML = tr;
        }
        //图片渲染
        goodsImg();
        function goodsImg(){
            let imagessrc = goodData.imagessrc;
            let img = '';
            let goodsImgBox = document.querySelector(".goods-img-box");
            imagessrc.forEach((item,index)=>{
                img += `<div class="goods-img">
            <img src="${item.b}" alt="" class="img-fluid">
        </div>`
            })
            goodsImgBox.innerHTML = img;
        }

        //模块导航开始
        goodsNav();
        function goodsNav(){
            $(".goods-nav-text span").on("click",function(){
                $(this).addClass("goods-nav-item-active").siblings("span").removeClass("goods-nav-item-active");
            })
            $(".goods-nav-item").eq(0).on("click",function(){
                returnTarget(window, $("#size-helper").offset().top+10);
            })
            $(".goods-nav-item").eq(1).on("click",function(){
                returnTarget(window, $("#goodsDetails").offset().top);
            })
            $(".goods-nav-item").eq(2).on("click",function(){
                returnTarget(window, $("#goods-img-tit").offset().top);
            })
            $(".goods-nav-item").eq(3).on("click",function(){
                returnTarget(window, $("#shopping-process").offset().top);
            })
            $(".goods-nav-item").eq(4).on("click",function(){
                returnTarget(window, $("#goods-guarantee").offset().top);
            })
            let navTop=()=>{
                if($(document).scrollTop() > $(".goods-nav-wrapper").offset().top){
                    $(".goods-nav").addClass("goods-topFixed").removeClass("container px-0");
                    $(".goods-nav-fixed").addClass("container px-0");
                    $(".goods-nav-cart").fadeIn();
                }else{
                    $(".goods-nav").removeClass("goods-topFixed").addClass("container px-0");
                    $(".goods-nav-fixed").removeClass("container px-0");
                    $(".goods-nav-cart").fadeOut();
                }
            }
            $(window).scroll(function (){
                navTop();
                $(".size-helper-table").each(function (i,ele){
                    if($(document).scrollTop() >= $(ele).offset().top){
                        $(".goods-nav-item").eq(i).addClass("goods-nav-item-active").siblings().removeClass("goods-nav-item-active");
                    }
                })
            })
        }
        //模块导航结束
// 商品详细结束

        //完成固定右侧导航栏颜色字体变化功能
        fixedRight()
        function fixedRight(){
            $(".toolbar-item").on("mouseenter mouseleave",function(){
                $(this).toggleClass("toolbar-active");
                $(this).find("span").toggleClass("toolbar-active");
            })
            //完成返回顶部功能
            let sliderbar = document.querySelector(".toolbar-wrap");
            let target = document.querySelector(".goods-nav-wrapper");
            let mainBox = document.querySelector("#size-helper");
            let targetTop = target.offsetTop;
            let sliderbarTop = sliderbar.offsetTop - targetTop;
            let mainTop = mainBox.offsetTop;

            document.addEventListener("scroll",function(){
                if(window.pageYOffset > targetTop){
                    sliderbar.style.position = 'fixed';
                    sliderbar.style.top = sliderbarTop + 'px';
                }else{
                    sliderbar.style.position = 'absolute';
                    sliderbar.style.top = '900px';
                }
                if(window.pageYOffset >= mainTop){
                    $(".toolbar").fadeIn();
                }else{
                    $(".toolbar").fadeOut();
                }
            })
            //完成返回页面顶部功能
            let topBtn = document.querySelector('.return-top');
            topBtn.addEventListener('click', function () {
                returnTarget(window, 0);
            });
        }
        //去往想要到达的像素
        function returnTarget(obj, target, callback) {
            clearInterval(obj.timer);
            obj.timer = setInterval(function () {
                var step = (target - window.pageYOffset) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (parseInt(window.pageYOffset) ==parseInt(target)) {
                    clearInterval(obj.timer);
                    callback && callback();
                }
                window.scroll(0, window.pageYOffset + step);
            }, 15);
        }
    })

    $(".addCartBtn").on("click",function (){
        addCar();
    })
    $(".goods-nav-cart").on("click",function (){
        addCar();
    })
    function addCar(){
        let queryString = location.search;
        let pid = queryString.split("=")[1];

        let qtyInput = document.querySelector("#qtyInput");
        let qty = qtyInput.value;

        let size = $("dl").children(".selected").eq(2).text();

        let shoppingPrice = $(".price").children("p").text();

        shoppingPrice=shoppingPrice/qty;


        //发送请求
        fetch(`add.car?pid=${pid}&qty=${qty}&size=${size}&shoppingPrice=${shoppingPrice}`).then(response=>response.json()).then(data=>{
            if(data.flag){
                alert(data.message);
            }
        })
    }
    $(".search button").on("click",function (){
        jumpToSearch()
    })
    // search函数
    function jumpToSearch() {
        let SearchInput = document.querySelector("#SearchInput");
        let keyWord = SearchInput.value;
        //对keyWord进行格式校验
        if (keyWord.trim().length == 0) {
            //keyWord为空 给出友好提示
            return "空空如也";
        } else {
            location.href = "searchProducts.html?keyWord=" + keyWord.trim();
        }
    }
})